package tv.youxing.android.ui;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.LinearLayout;

import com.kymjs.rxvolley.RxVolley;
import com.kymjs.rxvolley.client.HttpCallback;
import com.kymjs.rxvolley.client.HttpParams;
import com.kymjs.rxvolley.client.ProgressListener;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import tv.youxing.android.R;
import tv.youxing.android.custom.CustomToast;
import tv.youxing.android.entity.APKInfoDesModel;
import tv.youxing.android.utils.GsonUtils;
import tv.youxing.android.utils.StaticClass;
import tv.youxing.android.utils.UtilTools;

import static tv.youxing.android.R.id.webview;

/**
 * Created by Administrator on 2017/7/12.
 *
 *
 * // 2017年7月12日 15:07:44 还需要做version_code判断
 */


public class CheckAPKInfoActivity extends BaseActivity {


    @BindView(webview)
    WebView mWebView;
    @BindView(R.id.rootView)
    LinearLayout ll_root;
    @BindView(R.id.check)
    Button btnCheck;
    View rootView;


    APKInfoDesModel mAlldata;
    int version_code=-1;//版本号


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        rootView = getLayoutInflater().from(this).inflate(R.layout.activity_checkapkinfo, null);

        setContentView(rootView);
        ButterKnife.bind(this);

        version_code = UtilTools.getVersionCode();

        loadData();


    }

    private void loadData() {
        HttpParams params = new HttpParams();
        params.put("platform_type", 1);

        RxVolley.post(StaticClass.APKInfoDes, params, new HttpCallback() {
            @Override
            public void onSuccess(String t) {
                mAlldata = GsonUtils.GsonToBean(t, APKInfoDesModel.class);

                if (mAlldata.getCode() == 200) {
                    loadWEB();
                    loadUpdate();
                }
            }
        });
    }

    private void loadUpdate() {

        int vision = UtilTools.getVersion(CheckAPKInfoActivity.this);
        int new_vision = mAlldata.getResult().getVersion_code();

        if (vision < new_vision) {
            btnCheck.setEnabled(true);
            btnCheck.setBackgroundColor(R.color.color_tagColor);
            btnCheck.setText("可更新");
            btnCheck.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    download();
                }
            });
        } else {
            btnCheck.setEnabled(false);
            btnCheck.setBackgroundColor(R.color.color_gray);
            btnCheck.setText("当前已是最新版");
        }






    }


    void loadWEB() {
        mWebView.loadUrl(mAlldata.getResult().getApp_version_info_url());
        // 获取WebView属性
        WebSettings websettings = mWebView.getSettings();
        // 设置支持javascript代码
        websettings.setJavaScriptEnabled(true);

        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // 打开地址
                view.loadUrl(url);
                // 返回的是true，代表在webView控件中打开，否则在系统的浏览器中打开
                return true;
            }
        });
    }



    void download() {

        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {


            //下载进度(可选参数，不需要可不传)
            ProgressListener listener = new ProgressListener() {
                @Override
                public void onProgress(long transferredBytes, long totalSize) {
//                    tv.youxing.android.utils.L.d(transferredBytes + "======" + totalSize);
//                    tv.youxing.android.utils.L.d("正在下载:" + transferredBytes * 100 / totalSize
//                            + "%");

                    // transferredBytes 当前下载进度
                    // totalSize 总进度


                    btnCheck.setText("正在下载:" + transferredBytes * 100 / totalSize
                            + "%");
                }
            };

            //下载回调，内置了很多方法，详细请查看源码
            //包括在异步响应的onSuccessInAsync():注不能做UI操作
            //下载成功时的回调onSuccess()
            //下载失败时的回调onFailure():例如无网络，服务器异常等
            HttpCallback callback = new HttpCallback() {
                @Override
                public void onSuccessInAsync(byte[] t) {
                }

                @Override
                public void onSuccess(String t) {


                    btnCheck.setText("下载完成");

                    CustomToast.INSTANCE.showToast("安装包下载成功");
                    File mFile = new File(Environment.getExternalStorageDirectory().
                            getAbsolutePath() + "/youxing/file/" + "youxing.apk");

                    //判断文件后缀是否是apk
                    if(mFile.getName().endsWith(".apk")){
                        Intent install = new Intent();install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        install.setAction(android.content.Intent.ACTION_VIEW);
                        install.setDataAndType(Uri.fromFile(mFile),"application/vnd.android.package-archive");
                        startActivity(install);
                    }
                }

                @Override
                public void onFailure(int errorNo, String strMsg) {
                    CustomToast.INSTANCE.showToast("更新失败:" + strMsg);
                }
        };

        RxVolley.download(Environment.getExternalStorageDirectory().
                        getAbsolutePath() + "/youxing/file/" + "youxing.apk",
                mAlldata.getResult().getDownload_url(),
                listener, callback);

        } else {
            CustomToast.INSTANCE.showToast("没有SD卡");
        }


    }



    @Override
    protected void onResume() {
        super.onResume();
        mWebView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mWebView.onPause();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        ll_root.removeView(mWebView);
        mWebView.destroy();
    }
}
